<template>
  <div class="time-display">
    <span style="padding-right: 6px;">{{ currentDate }}</span><span>{{ currentTime }}</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      currentTime: "", // 时分秒
      currentDate: "", // 年月日
    };
  },
  mounted() {
    // 初始化时更新一次
    this.updateTime();
    // 每秒更新一次
    this.timer = setInterval(() => {
      this.updateTime();
    }, 1000);
  },
  beforeDestroy() {
    // 组件销毁时清除定时器，防止内存泄漏
    clearInterval(this.timer);
  },
  methods: {
    updateTime() {
      const now = new Date();

      // 格式化时间（时分秒，补零）
      const hours = this.padZero(now.getHours());
      const minutes = this.padZero(now.getMinutes());
      const seconds = this.padZero(now.getSeconds());
      this.currentTime = `${hours}:${minutes}:${seconds}`;

      // 格式化日期（年月日）
      const year = now.getFullYear();
      const month = this.padZero(now.getMonth() + 1); // 月份从0开始
      const day = this.padZero(now.getDate());
      const week = ["日", "一", "二", "三", "四", "五", "六"][now.getDay()];
      this.currentDate = `${year}-${month}-${day} 星期${week}`;
    },
    // 补零函数（如 9 → '09'）
    padZero(num) {
      return num < 10 ? `0${num}` : num;
    },
  },
};
</script>

<style scoped>
.time-display {
  font-size: 16px;
  color: #333;
  line-height: 1.8;
  display: inline-block;
  color: #cbd5e1;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 16px;
  border: 1px solid rgba(59, 130, 246, 0.3);
  box-shadow: 0 0 10px rgba(59, 130, 246, 0.2);
  transition: all 0.3s ease;
  padding: 6px 15px;
}
.time-display:hover {
  background: rgba(59, 130, 246, 0.2);
  box-shadow: 0 0 20px rgba(59, 130, 246, 0.3);
  transform: translateY(-2px);
}
</style>
